<template>
  <el-card class="box-card-1">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>选择前景图像</span>
          </div>
          <div class="text-center">
            <el-upload
              class="upload-demo"
              :action="uploadAction"
              :on-remove="removeForeground"
              :file-list="foregroundList"
              :on-change="handleFrontgroundChange"
              list-type="picture-card"
              :before-upload="beforeFrontgroundUpload"
              :auto-upload="false"
              :on-success="handleForegroundSuccess"
              accept="image/*"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </div>
          <div v-for="(file, index) in foregroundList" :key="'foreground' + index" class="image-preview" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>选择背景图像</span>
          </div>
          <div class="text-center">
            <el-upload
              class="upload-demo"
              :action="uploadAction"
              :on-change="handleBackgroundChange"
              :file-list="backgroundList"
              :show-file-list="true"
              list-type="picture-card"
              :before-upload="beforeBackgroundUpload"
              :on-success="handleBackgroundSuccess"
              :auto-upload="false"
              accept="image/*"
              :on-exceed="handleExceed"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </div>
          <div v-if="backgroundList.length > 0" class="image-preview" />
        </el-card>
      </el-col>
    </el-row>
    <div class="text-center button-container"> <!-- 合成图像按钮居中 -->
      <el-button type="primary" @click="openImagesWindow">合成图像</el-button>
      <el-dialog title="合成图像" :visible.sync="isR">
        <div style="display: flex">
          <div class="image-editor" style="width: 75%; height: auto">
            <div class="background" style="width: 100%; height: auto" @click="deselectForeground" />
            <div class="foreground-container" style="width: 100%; height: auto">
              <img
                id="backImg"
                :src="uploadImageUrl"
                style="position: absolute ;left: 0; max-width: 100%;  max-height: 100%"
                alt="背景图片"
              >
              <div
                v-for="(url, i) in selectedForeImg"
                :id="'foreImg' + i"
                :key="i"
                class="foreImg-wrapper"
                :class="{ foreImg: true, 'selected': selectedImageIndex === i, 'highlighted': selectedImageIndex === i }"
                :style="{ zIndex: selectedImageIndex === i ? 1 : 0 , left: '0px', top: '0px'}"
                @mousedown="startDrag($event, i)"
              >
                <img
                  :src="url"
                  class="foreImg"
                  :style="{ transformOrigin: 'top left' }"
                >
                <div class="delete-button" @click="deleteImage(i)">×</div>
              </div>
              <!--                   :style="getImageStyle(index)"
                   @click="clickForeImg(index)"-->
            </div>
          </div>
          <div class="image-editor" style="width: 25%">
            <span>前景图像列表</span>
            <div v-for="(foreground, key) in foregroundList" :key="key" @click="selectForeground(key)">
              <img :src="foreground.url" style="width: 100%; height: auto" alt="Image">
            </div>
          </div>
        </div>
        <el-button type="primary" @click="combineImages">合成图像</el-button>
      </el-dialog>

    </div>
    <!-- 合成进度框 -->
    <div v-if="isCombining" class="progress-box">
      合成中，请稍候...
      <el-progress :percentage="progressPercentage" :status="progressStatus" />
    </div>
    <div v-if="isCombiningSuccess">
      合成成功！
    </div>

    <!-- 合成结果展示 -->
    <div v-if="isCombiningSuccess" class="combined-image-container">
      <img :src="combinedImageUrl" alt="Combined Image">
      <el-button type="primary" @click="downloadCombinedImage">下载图片</el-button>
      <el-button type="primary" @click="editImages">再次编辑</el-button>
    </div>
  </el-card>
</template>

<script>

export default {
  data() {
    return {
      selectedImageIndex: null,
      uploadAction: '//jsonplaceholder.typicode.com/posts/', // 替换为您的上传处理URL
      foregroundList: [],
      files: [],
      backFile: [],
      currentForeImg: 0,
      backgroundList: [],
      isSelected: [],
      scale: 1,
      isR: false,
      url: {},
      length: 0,
      selectedForegroundIndex: 0,
      isMouseDown: false,
      startForeImgX: 0,
      startForeImgY: 0,
      isSame: -1,
      startX: 0,
      startY: 0,
      ForeImgX: 0,
      ForeImgY: 0,
      showForeImg: '',
      selectedForeImg: [],
      foregroundImages: [
        'src/th.jpg',
        'src/th.jpg'
        // Add more foreground images as needed
      ],
      uploadImageUrl: '',
      isCombining: false, // 合成图片判断
      isCombiningSuccess: false, // 合成成功判断
      progressPercentage: 0, // 进度条的百分比
      progressStatus: 'active', // 进度条的状态，可以是'success', 'exception', 'active'
      combinedImageUrl: null, // 合成后的图片URL
      // position: { x1: 0, y1: 0, x2: 0, y2: 0 }, // 前景图片在背景图片上的坐标
      position: [],
      positionRightDown: [0, 0, 0, 0],
      showUploadButton: true, // 显示背景上传按钮
      backImgSize: []
    }
  },
  mounted() {
    let scale = 1
    var foreImg = document.getElementById('foreImg' + this.currentForeImg)
    console.log('foreImg:', foreImg)
    foreImg.onwheel = (e) => {
      if (e.deltaY > 0) {
        scale += 0.05
      } else {
        scale -= 0.05
      }
      scale = Math.min(Math.max(0.1, scale), 5)
      foreImg.style.transform = `scale(${scale})`
    }
  },

  methods: {
    // 这个index是selectedForeImg中的index
    deleteImage(index) {
      this.selectedForeImg.splice(index, 1)
      this.files.splice(index, 1)
      this.position = [0, 0]
      // this.position.splice(index, 1)
    },
    openImagesWindow() {
      // TODO: 在这里添加合成图片的逻辑
      // 然后跳转到新的页面
      console.log('前景图像:', this.foregroundList)
      console.log('uploadImageUrl', this.uploadImageUrl)
      // console.log(this.foregroundList)
      // console.log(this.backgroundList)
      this.foregroundList.forEach(file => {
        console.log(`文件名: ${file.name}, URL: ${file.url}`)
      })
      console.log('背景图像:')
      this.backgroundList.forEach(file => {
        console.log(`文件名: ${file.name}, URL: ${file.url}`)
      })
      this.isR = true
    },
    selectForeground(index) {
      // this.scaleImg()
      this.url[this.length] = this.foregroundList[index].url
      this.position = [0, 0]
      this.files.push(this.foregroundList[index].file)
      this.selectedForeImg.push(this.foregroundList[index].url)
      console.log('file:::', this.foregroundList[index].file.raw)
      this.length++
    },
    deselectForeground() {
      this.selectedForegroundIndex = null
    },
    startDrag(event, index) {
      this.currentForeImg = index
      if (this.isSame !== index) {
        this.startForeImgX = this.position[0]
        this.startForeImgY = this.position[1]
        this.ForeImgX = this.startForeImgX
        this.ForeImgY = this.startForeImgY
      }
      this.isSame = index
      console.log('this.positionStart:', this.position)
      // 图片highlight
      this.highlightedIndex = index

      console.log('event,', event)
      this.isMouseDown = true
      event.preventDefault()
      const backgroundElement = document.getElementById('backImg')
      const rectBack = backgroundElement.getBoundingClientRect()
      this.backImgSize[0] = rectBack.width
      this.backImgSize[1] = rectBack.height
      console.log('rectBack:', rectBack.height, rectBack.width)
      const foregroundElement = event.target // <img/>
      const backRec = backgroundElement.getBoundingClientRect()
      const rect = foregroundElement.getBoundingClientRect()
      console.log('rect:', rect)

      // this.dragOffsetX = event.clientX - rect.left  // 鼠标相对于背景图片的位置（起始）
      // this.dragOffsetY = event.clientY - rect.top
      this.startX = event.clientX
      this.startY = event.clientY

      document.onmousemove = (event) => {
        if (this.isMouseDown === true) {
          console.log('开始拖拽')
          if (backgroundElement) {
            this.ForeImgX = event.clientX - this.startX + this.startForeImgX
            this.ForeImgY = event.clientY - this.startY + this.startForeImgY

            if (this.ForeImgX < 0 - backRec.width) {
              this.ForeImgX = 0
            } else if (this.ForeImgX + rect.width > backRec.width + backRec.width) {
              this.ForeImgX = backRec.width - rect.width
            }
            if (this.ForeImgY < 0 - backRec.height) {
              this.ForeImgY = 0
            } else if (this.ForeImgY + rect.height > backRec.height + backRec.height) {
              this.ForeImgY = backRec.height - rect.height
            }
            console.log('rect.width:', rect.width, rect.height)
            this.position = [this.ForeImgX, this.ForeImgY]
            this.positionRightDown = [this.position[0], this.position[1], this.position[0] + rect.width, this.position[1] + rect.height]
            console.log('onmousedown, position', this.positionRightDown)
            // console.log("backRect", backRec.height, backRec.width)
            // console.log("rect", rect.height, rect.width)
            // console.log("this.ForeImgX:", this.ForeImgX, this.ForeImgY)
            console.log('this.position', this.position)
            // console.log('this.startForeImgX', this.startForeImgX, this.startForeImgY, 'thisForeImgX', this.ForeImgX, this.ForeImgY)
            this.$el.querySelector(`#foreImg${index}`).style.left = this.position[0] + 'px'
            this.$el.querySelector(`#foreImg${index}`).style.top = this.position[1] + 'px'
          }
        }
      }

      document.onmouseup = (event) => {
        this.startForeImgX = this.ForeImgX
        this.startForeImgY = this.ForeImgY
        console.log('停止拖拽')
        this.isMouseDown = false
      }

      document.onwheel = (event) => {
        if (event.deltaY > 0) {
          this.scale += 0.05
        } else {
          this.scale -= 0.05
        }
        this.scale = Math.min(Math.max(0.1, this.scale), 5)
        this.$el.querySelector(`#foreImg${index}`).style.transform = `scale(${this.scale})`
        // 计算缩放后的图片坐标
        console.log('this.position:', this.position)
        const rect1 = foregroundElement.getBoundingClientRect()
        this.positionRightDown = [this.position[0], this.position[1], this.position[0] + rect1.width, this.position[1] + rect1.height]
        console.log('onwheel, position', rect1.width, rect1.height, rect.width, rect.height, this.positionRightDown)
        // console.log("rectHeight:", rect.width, rect.height)
        // console.log('this.startX', this.startX, this.startY, 'event', event.clientX, event.clientY)
      }
      this.selectedImageIndex = index
    },
    handleForegroundSuccess(response, file) {
      // 前景图上传成功后的处理
      this.foregroundList = [{ name: file.name, url: URL.createObjectURL(file.raw) }]
      console.log('前景图片列表', this.foregroundList)
    },
    handleBackgroundSuccess(response, file) {
      // 背景图上传成功后的处理
      this.backgroundList = [{ name: file.name, url: URL.createObjectURL(file.raw) }]
      this.showUploadButton = false
    },
    handleRemove(file, fileList) {
      // 移除文件的处理逻辑
    },
    removeForeground(index) {
      this.foregroundList.splice(index, 1)
    },
    removeBackground(index) {
      this.backgroundList.splice(index, 1)
      this.backFile.splice(index, 1)
      this.showUploadButton = true
    },
    submitUpload(type) {
      if (type === 'background') {
        this.$refs.uploadBackground.submit()
      }
      if (type === 'frontground') {
        this.$refs.uploadFrontground.submit()
      }
    },
    // 新增方法用于在新窗口中放大和预览图片
    handlePreview(file) {
      window.open(file.url)
    },
    beforeBackgroundUpload() {
      // 仅允许一张背景图片
      console.log('搜索视频', this.backgroundList)
      if (this.backgroundList.length >= 1) {
        this.$message.error('只能添加一张背景图像')
        return false
      }
      return true
    },
    beforeFrontgroundUpload() {
      // 仅允许一张背景图片
      console.log('搜索视频', this.foregroundList)
      return true
    },
    handleFrontgroundChange(file, fileList) {
      // 在这里处理前端图片预览，不需要上传到后端
      this.foregroundList.push({ name: file.name, url: URL.createObjectURL(file.raw), file: file })
      console.log(this.foregroundList[0].url)
    },
    handleBackgroundChange(file, fileList) {
      // 在这里处理前端图片预览，不需要上传到后端
      if (this.backFile.length) {
        this.backFile = []
      }
      this.backFile.push(file)
      this.backgroundList = [{ name: file.name, url: URL.createObjectURL(file.raw) }]
      const uploadImage = fileList[fileList.length - 1]
      console.log(uploadImage.url)
      if (uploadImage && uploadImage.url) {
        this.uploadImageUrl = uploadImage.url
      }
    },
    combineImages() {
      this.progressPercentage = 0
      this.progressStatus = 'active'
      if (this.positionRightDown[0] === 0 ||
        this.positionRightDown[1] === 0 ||
        this.positionRightDown[2] === 0 ||
        this.positionRightDown[3] === 0) {
        var img = new Image()
        // 假定前景图片仅一张
        img.src = this.selectedForeImg[0]
        console.log('imgSrc:', img.src, img.height, img.width)
        this.positionRightDown[0] = 0
        this.positionRightDown[1] = 0
        this.positionRightDown[2] = img.width
        this.positionRightDown[3] = img.height
        console.log('positionSSSSS', this.positionRightDown)
      }
      // TODO: 在这里添加合成图片的逻辑
      this.isCombining = true
      this.isCombiningSuccess = false
      this.combinedImageUrl = null

      this.foregroundList.forEach(file => {
        console.log(`文件名: ${file.name}, URL: ${file.url}`)
      })
      console.log('背景图像:')
      this.backgroundList.forEach(file => {
        console.log(`文件名: ${file.name}, URL: ${file.url}`)
      })

      this.isR = false

      // 使用 setTimeout 来模拟异步操作
      const intervalId = setInterval(() => {
        if (this.progressPercentage < 200) {
          this.progressPercentage += 10
        } else {
          clearInterval(intervalId)
          this.progressStatus = 'success'
          this.isCombiningSuccess = true
          this.isCombining = false
        }
      }, 1000)
      var orgWid = document.getElementById('backImg').naturalWidth
      var orgHgh = document.getElementById('backImg').naturalHeight
      const pos = [orgWid * this.positionRightDown[0] / this.backImgSize[0], orgHgh * this.positionRightDown[1] / this.backImgSize[1], orgWid * this.positionRightDown[2] / this.backImgSize[0], orgHgh * this.positionRightDown[3] / this.backImgSize[1]]
      const formData = new FormData()
      console.log('this.files[0].raw:', this.files[0].raw)
      formData.append('foreground', this.files[0].raw)
      formData.append('background', this.backFile[0].raw)
      formData.append('bbox', JSON.stringify(pos))
      console.log('JSON:', JSON.stringify(pos))
      console.log('formData:', formData.keys)

      // 发送后端前景、背景图片、位置信息
      this.$store.dispatch('systemconfig/postPos', formData)
        .then(response => {
          this.combinedImageUrl = 'data:image/jpg;base64,' + response.data
          console.log('response:', response.data)
        })
        .catch(error => {
          console.error('获取根目录失败:', error)
        })
      //   this.$router.push({ path: '/new-page' }) // 使用vue-router进行页面跳转
    },
    handleExceed(e) {
      this.$message({
        type: 'warning',
        message: '只能上传一个文件!'
      })
    },
    downloadCombinedImage() {
      if (this.combinedImageUrl) {
        fetch(this.combinedImageUrl)
          .then(response => {
            if (response.ok) {
              return response.blob()
            }
            throw new Error('Network response was not ok.')
          })
          .then(blob => {
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = 'combined-image.png'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
          })
          .catch(error => {
            console.error('There was a problem with the fetch operation:', error)
          })
      }
    },
    editImages() {
      // 用模态窗口的缓存
      this.isR = true
    },
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },
    dataURLtoFile(dataurl, type = 'application/octet-stream') {
      var bstr = window.atob(dataurl)
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type })
    }
  }
}
</script>

<style scoped>
.highlighted {
  border: 2px solid red
}

.selected {
  z-index: 1;
  /* 选中的图片显示在最上层 */
}

.foreImg {
  position: absolute;
  left: 0
}

.image-editor {
  position: relative;
  width: 800px;
  /* Adjust width as needed */
  height: 600px;
  /* Adjust height as needed */
  border: 1px solid #ccc;
  /* Optional: add border for visualization */
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 70%;
  height: 100%;
  background-image: url('https://img-blog.csdnimg.cn/20190918202559573.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2E0MTcxMjUxMTE=,size_16,color_FFFFFF,t_70');
  background-size: cover;
}

.foreground {
  position: absolute;
  width: 100px;
  /* Adjust width of foreground images as needed */
  height: 100px;
  /* Adjust height of foreground images as needed */
  background-size: contain;
  background-repeat: no-repeat;
  cursor: pointer;
}

.foreground.selected {
  border: 2px solid red;
  /* Highlight selected foreground image */
}

.box-card-1 {
  margin: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.box-card {
  width: 650px;
  border: 1px solid #E4E7ED;
}

.text-center {
  text-align: center;
}

.upload-demo .el-upload {
  border: none;
}

.image-preview {
  position: relative;
  display: inline-block;
  margin: 10px;
}

.image {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.button-container {
  margin-top: 10px
}

.foreImg-wrapper {
  position: absolute;
  display: inline-block;
}

.delete-button {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: #ff0000;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  line-height: 20px;
}

/* .el-upload-list--picture-card .el-upload-list__item {
    padding: 10px;
  } */
</style>
